const request = require('request');
const schedule = require('node-schedule');
const { getStockTransactionDataList } = require('./api');
const { stompConnect, stompDisconnect } = require('./stomp');
const { kafkaConnect } = require('./kafka');
const { changeTwoDecimal_f } = require('./util');

exports.scheduleCronstyle = () => {
  // 每隔5秒执行一次
  let rule = new schedule.RecurrenceRule();
  // const times = [1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56];
  const times = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29,
    31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59];
  rule.minute = times;
  // rule = '1-10 * * * * *';
  schedule.scheduleJob(rule, () => {
    getStockTransactionDataList().then((result) => {
      // let stockTransactionDataList = {};
      for (let i in result) {
        let stockTransactionData = result[i];
        let paramArray = stockTransactionData.split('=');
        // 代码
        let code = paramArray[0].split('_')[2].substring(2, paramArray[0].split('_')[2].length);
        let dataArray = paramArray[1].substring(1, paramArray[1].length - 3).split(',');
        // 名称
        let name = dataArray[0];
        // 最新价
        let newestPrice = dataArray[3];
        // 今开
        let todayOpenPrice = dataArray[1];
        // 昨收
        let yestodayPrice = dataArray[2];
        // 最高价
        let highestPrice = dataArray[4];
        // 最低价
        let lowestPrice = dataArray[5];
        // 涨跌额
        let upDownPrice = changeTwoDecimal_f(newestPrice - yestodayPrice);
        // 涨跌幅
        let upDownPercentage = changeTwoDecimal_f(upDownPrice / yestodayPrice * 100);
        // 股票交易信息对象
        stockTransactionData = {
          code, name, newestPrice, todayOpenPrice, yestodayPrice, highestPrice,
          lowestPrice, upDownPrice, upDownPercentage
        };
        // stockTransactionDataList.push(stockTransactionData);

        // 发送到消息服务器
        stompConnect(stockTransactionData);
        // kafkaConnect(stockTransactionData);
      }
    });
  })
}
